package com.aracky.common.util;

import lombok.SneakyThrows;
import org.springframework.http.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URLEncoder;
import java.util.Arrays;

/**
 * @Author zengzhiping
 * @BelongsPackage com.aracky.common.util
 * @CreateTime 2022-08-09
 * @Description
 */
public class FileUtil {

    /**
     * 文件单位
     */
    public static final String B_UNIT = "B";
    public static final String K_UNIT = "K";
    public static final String M_UNIT = "M";
    public static final String G_UNIT = "G";

    /**
     * 图片类型 jpg、jpeg、png
     */
    public static String[] IMAGE_TYPE = {"jpg", "png", "jpeg"};

    /**
     * 判断文件是否超过限制
     *
     * @param len  文件长度
     * @param size 文件限制长度
     * @param unit 文件单位
     * @return
     */
    public static boolean checkFileSize(Long len, int size, String unit) {
        double fileSize;
        switch (unit.toUpperCase()) {
            case K_UNIT:
                fileSize = (double) len / 1024;
                break;
            case M_UNIT:
                fileSize = (double) len / 1048576;
                break;
            case G_UNIT:
                fileSize = (double) len / 1073741824;
                break;
            default:
                fileSize = (double) len;
                break;
        }
        if (fileSize > size) {
            return false;
        }
        return true;
    }

    /**
     * 检查文件是否为图片类型
     *
     * @param file
     * @return
     */
    public static boolean checkFileIsImage(MultipartFile file) {
        //文件名称
        String realFileName = file.getOriginalFilename();
        //文件后缀
        String suffix = realFileName.substring(realFileName.lastIndexOf(".") + 1);

        if (Arrays.asList(IMAGE_TYPE).contains(suffix)) {
            return true;
        }
        return false;
    }

    /**
     * byte转File对象
     * @param fileBytes
     * @return
     */
    @SneakyThrows
    public static File byteToFile(byte[] fileBytes){
        try{
            File file = null;
            OutputStream output = new FileOutputStream(file);
            BufferedOutputStream bufferedOutput = new BufferedOutputStream(output);
            bufferedOutput.write(fileBytes);
            return file;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 展示图片
     * @param fileName
     * @param in
     * @return
     */
    public static ResponseEntity<byte[]> showImage(String fileName, InputStream in)  {
        //创建字节输入流
        ByteArrayOutputStream baos = convertOutputStream(in);
        return getResponseEntity(fileName, baos.toByteArray(),MediaType.IMAGE_PNG);
    }

    /**
     * 下载文件
     * @param fileName
     * @param fileByte
     * @return
     */
    public static ResponseEntity<byte[]> downloadFile(String fileName, byte[] fileByte)  {
        //创建字节输入流
        return getResponseEntity(fileName, fileByte,MediaType.APPLICATION_OCTET_STREAM);
    }

    /**
     * 下载文件
     * @param fileName
     * @param in
     * @return
     */
    public static ResponseEntity<byte[]> downloadFile(String fileName, InputStream in)  {
        //创建字节输入流
        ByteArrayOutputStream baos = convertOutputStream(in);
        return getResponseEntity(fileName, baos.toByteArray(),MediaType.APPLICATION_OCTET_STREAM);
    }


    /**
     * 下载文件
     * @param fileName
     * @param baos
     * @return
     */
    public static ResponseEntity<byte[]>  downloadFile(String fileName,ByteArrayOutputStream baos)  {
        return getResponseEntity(fileName, baos.toByteArray(),MediaType.APPLICATION_OCTET_STREAM);
    }

    /**
     * 设置响应信息
     * @param fileName
     * @param fileByte
     * @return
     */
    @SneakyThrows
    private static ResponseEntity<byte[]> getResponseEntity(String fileName, byte[] fileByte, MediaType mediaType)  {
        HttpHeaders httpHeaders = new HttpHeaders();
        // 通知浏览器以下载文件方式打开
        ContentDisposition contentDisposition =
                ContentDisposition.builder("attachment").filename(fileName).build();
        httpHeaders.setContentDisposition(contentDisposition);
        //编码
        fileName = URLEncoder.encode(fileName, "utf-8");
        httpHeaders.add("fileName",fileName);
        // application/octet_stream设置MIME为任意二进制数据
        httpHeaders.setContentType(mediaType);
        return new ResponseEntity<byte[]>(fileByte, httpHeaders, HttpStatus.OK);
    }



    /**
     * 转换流
     * @param input
     * @return
     */
    public static ByteArrayOutputStream convertOutputStream(InputStream input) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        try {
            while ((len = input.read(buffer)) > -1) {
                baos.write(buffer, 0, len);
            }
            baos.flush();
        } catch (IOException e) {
        } finally {
            try {
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return baos;
    }

}
